﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DBControl;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Text;
using System.IO;
using Top;
using Top.Api;
using Top.Api.Response;
using Top.Api.Request;
using System.Web.Security;

namespace ProjectX
{
    public partial class AjaxWeb : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            string type = "";
            if (Request.RequestType == "GET")
            {
                type = Request.QueryString["type"].ToString();
            }
            else
            {
                type = Request.Form["type"];
            }
            string result = "";
            switch (type)
            {
                //case "cit":
                //    result = BindCitSelect();
                //    Response.Write(result);
                //    Response.End();
                //    return;
                //case "allcit":
                //    string pageNo = Request.QueryString["pageNo"].ToString();
                //    result = BindAllCit(pageNo);
                //    Response.Write(result);
                //    Response.End();
                //    return;
                //case "pageCount":
                //    result = GetPageCount();
                //    Response.Write(result);
                //    Response.End();
                //    return;
                //case "insert":
                //    result = InsertBuyinfo().ToString();
                //    Response.Write(result);
                //    Response.End();
                //    return;
                case "addbuy":
                    result = addbuy().ToString();
                    Response.Write(result);
                    Response.End();
                    return;
                case "regedit":
                    result = regedit();
                    Response.Write(result);
                    Response.End();
                    return;
                case "collect":
                    result = collect();
                    Response.Write(result);
                    Response.End();
                    return;
                case "ipclick":
                    result = ipclick();
                    Response.Write(result);
                    Response.End();
                    return;
                case "bindcate":
                    result = bindcate();
                    Response.Write(result);
                    Response.End();
                    return;
                case "getUser":
                    result = getUser();
                    Response.Write(result);
                    Response.End();
                    return;
                //case "closebuy":
                //    result = closebuy();
                //    Response.Write(result);
                //    Response.End();
                //    return;
                //case "updatepass":
                //    result = updatepass();
                //    Response.Write(result);
                //    Response.End();
                //    return;
                case "updateuser":
                    result = updateuser();
                    Response.Write(result);
                    Response.End();
                    return;
                default:
                    return;
            }
        }
        private string updateuser()
        {
            string email = Request.Form["emailbox"];
            string tbname = Request.Form["tbname"];
            string updateuser = "UPDATE UserRegister SET [email] = '" + email + "',Tbname='" + tbname + "' WHERE userName='" + Session["userNick"] + "'";
            SqlDbHelper sdh = new SqlDbHelper();
            try
            {
                if (sdh.ExecuteNonQuery(updateuser) != 0)
                {
                    return "ok";
                }
                else
                {
                    return "";
                }
            }
            catch (Exception)
            {
                return "";
            }
        }
        //private string updatepass()
        //{
        //    string getold = "SELECT passWord FROM UserRegister WHERE userName = '" + Session["userNick"] + "'";
        //    string oldpass = FormsAuthentication.HashPasswordForStoringInConfigFile(Request.Form["oldpass"], "MD5"); ;
        //    string newpass = FormsAuthentication.HashPasswordForStoringInConfigFile(Request.Form["newpass"], "MD5");
        //    string uppass = "UPDATE UserRegister SET passWord = '"+ newpass +"' WHERE userName = '"+ Session["userNick"] +"'";
        //    SqlDbHelper sdh = new SqlDbHelper();
        //    try
        //    {
        //        if (oldpass.Equals(sdh.ExecuteScalar(getold)))
        //        {
        //            if (sdh.ExecuteNonQuery(uppass) != 0)
        //            {
        //                return "ok";
        //            }
        //            else
        //            {
        //                return "";
        //            }
        //        }
        //        else
        //        {
        //            return "olderror";
        //        }
        //    }
        //    catch (Exception)
        //    {
        //        return "";
        //    }
        //}

        //private string closebuy() 
        //{
        //    string buyid = Request.Form["buyid"];
        //    string closestr = "UPDATE BuyersinfoR SET [Status] = 1 WHERE Id='" + buyid + "'";
        //    try
        //    {
        //        SqlDbHelper sdh = new SqlDbHelper();
        //        int i = sdh.ExecuteNonQuery(closestr);
        //        if (i != 0)
        //        {
        //            return "ok";
        //        }
        //        else
        //        {
        //            return "norow";
        //        }
        //    }
        //    catch (Exception)
        //    {
        //        return "error";
        //    }
        //}

        //private string ConnString()
        //{
        //    SystemLib sl = new SystemLib();
        //    string connStr = "";
        //    string datasource = ConfigurationManager.AppSettings["SqlServer"];
        //    string dataname = ConfigurationManager.AppSettings["SqlDataName"];
        //    string uid = ConfigurationManager.AppSettings["SqlUid"];
        //    string pwd = sl.Decrypto(ConfigurationManager.AppSettings["SqlPwd"]);
        //    connStr = "Data Source=" + datasource + ";Initial Catalog=" + dataname + ";User ID=" + uid + ";PassWord=" + pwd;
        //    return connStr;
        //}

        private string BindCitSelect()
        {
            StringBuilder result = new StringBuilder();
            try
            {
                ITopClient itop = new DefaultTopClient(SystemLib.appurl, SystemLib.appkey, SystemLib.appsecret);
                if (Request.Form["cid"].Equals("0"))
                {
                    return "";
                }

                ItemcatsGetRequest itemcats = new ItemcatsGetRequest();
                itemcats.Fields = "cid,parent_cid,name,is_parent,status";
                itemcats.Cids = Request.Form["cid"];
                ItemcatsGetResponse itemcatsresponse = itop.Execute(itemcats);
                if (itemcatsresponse.ItemCats[0].IsParent)
                {
                    itemcats.Cids = "";
                    itemcats.ParentCid = long.Parse(Request.Form["cid"]);
                    ItemcatsGetResponse icgr = itop.Execute(itemcats);
                    foreach (var item in icgr.ItemCats)
                    {
                        if (item.Status.Equals("normal"))
                        {
                            if (item.IsParent)
                            {
                                result.Append("<option value=" + item.Cid + ">" + item.Name + "</option>");
                            }
                            else
                            {
                                result.Append("<option value=" + item.Cid + ">" + item.Name + "</option>");
                            }

                        }
                    }
                }
                else
                {
                    ItempropsGetRequest itemprop = new ItempropsGetRequest();
                    itemprop.Fields = "pid,name,prop_values,status";
                    itemprop.Cid = long.Parse(Request.Form["cid"]);
                    itemprop.IsKeyProp = true;
                    itemprop.IsEnumProp = true;
                    itemprop.ParentPid = 0;
                    ItempropsGetResponse itemprop_response = itop.Execute(itemprop);
                    if (itemprop_response.ItemProps.Count > 0)
                    {
                        ItempropvaluesGetRequest itemprop_values = new ItempropvaluesGetRequest();
                        itemprop_values.Cid = long.Parse(Request.Form["cid"]);
                        itemprop_values.Fields = "name,status,pid";
                        foreach (var item in itemprop_response.ItemProps)
                        {
                            itemprop_values.Pvs = item.Pid.ToString();
                            ItempropvaluesGetResponse itemvalue_response = itop.Execute(itemprop_values);
                            foreach (var childitem in itemvalue_response.PropValues)
                            {
                                if (childitem.Status.Equals("normal"))
                                {
                                    result.Append("<option value=" + childitem.Cid + ">" + childitem.Name + "</option>");
                                }
                            }

                        }
                    }
                }
            }
            catch (Exception ex)
            {
                result.Append(ex.Message);
            }
            return result.ToString();
        }

        //private string BindAllCit(string pageNo)
        //{
        //    StringBuilder result = new StringBuilder();

        //    SqlDbHelper sdh = new SqlDbHelper(this.ConnString());
            
        //    //调用分页存储过程
        //    SqlParameter p1 = new SqlParameter("@tablename","CitView");//视图名或表名
        //    SqlParameter p2 = new SqlParameter("@pagerow",10);         //每页显示记录数 
        //    SqlParameter p3 = new SqlParameter("@pagenow",pageNo);     //当前显示第几页 
        //    SqlParameter p4 = new SqlParameter("@ordercol", "sort_order");//排序字段

        //    SqlParameter[] paras = new SqlParameter[]{p1,p2,p3,p4};

        //    SqlDataReader dr = sdh.ExecuteReader("sp_page", System.Data.CommandType.StoredProcedure, paras);

        //    while (dr.Read())
        //    {

        //        //SqlDataReader drchild = sdh.ExecuteReader("SELECT cid,[Name] FROM Category WHERE parent_cid = " + dr["Cid"] + " and [Status]='normal' order by sort_order");
        //        SqlDataReader drchild = sdh.ExecuteReader("SELECT DISTINCT Category.cid,Category.[Name],Category.Sort_order FROM BuyersinfoR,Category WHERE BuyersinfoR.cateid = Category.cid AND Category.Parent_cid=" + dr["Cid"] + " and Category.[Status]='normal' order by sort_order");
        //        string resultchild = "";
                
        //        if (drchild.HasRows)
        //        {
        //            resultchild += "<ul>";
        //            while (drchild.Read())
        //            {
        //                resultchild += "<li><a href='' onclick=\"reloadframe(" + drchild["cid"] + ",'" + dr["Name"] + "','" + drchild["Name"] + "');return false;\" style='color:#1c94c4;text-decoration:none;'>" + drchild["Name"] + "</a></li>";
        //            }
        //            resultchild += ("</ul>");
        //        }

        //        //string htmlStr = "<div><h3><a href='' onclick=\"reloadframe(" + dr["cid"] + ",'" + dr["Name"] + "','" + "" + "');return false;\">" + dr["Name"] + "</a></h3>";
        //        string htmlStr = "<div><h3 id="+ dr["cid"] +"><a href=''>" + dr["Name"] + "</a></h3>";

        //        result.Append(htmlStr + resultchild + "</div>");
        //    }
        //    return result.ToString();
        //}

        //private string GetPageCount()
        //{
        //    SqlDbHelper sdh = new SqlDbHelper(this.ConnString());
        //    string result = "";
        //    int count = int.Parse(sdh.ExecuteScalar("SELECT COUNT(*) FROM CitView").ToString());
        //    if (count%10 == 0)
        //    {
        //        result = (count / 10).ToString();
        //    }
        //    else
        //    {
        //        result = ((count / 10) + 1).ToString();
        //    }

        //    return result;
        //}

        //private int InsertBuyinfo()
        //{
        //    int cate = int.Parse(Request.Form["Gcid"]);
        //    int pcid = int.Parse(Request.Form["Gpcid"]);
            
        //    string cidtree = Request.Form["Gcidtree"];
        //    string title = Request.Form["Gtitle"];
        //    string owner = Request.Form["Gowner"];
        //    string pricem = Request.Form["Gpricem"];
        //    string pricex = Request.Form["Gpricex"];
        //    string datetime = Request.Form["Gdatetime"];
        //    int count = int.Parse(Request.Form["Gcount"]);
        //    string imgname = Request.Form["Gimgpath"];
        //    string sheng = Request.Form["Gsheng"];
        //    string shi = Request.Form["Gshi"];
        //    string infomation = Request.Form["Ginfomation"];
        //    string name = Request.Form["Gname"];
        //    string keyprop = Request.Form["Gkeyprop"];
        //    string imgsrc = "";
        //    string cittextTree = Request.Form["GcidtextTree"];

        //    //string insSql = "INSERT INTO BuyersinfoR(ReleaseName,Information,ExpectpricesMax,ExpectpricesMin,Responder,Respondcount,Cateid,Catetext,Overtime,VolumeCount,Province,City,Title,[Owner],imgsrc,[Count],[name],Keyprop) ";
        //    if (pricex == "")
        //    {
        //        pricex = "0";
        //    }

        //    if (pricem == "")
        //    {
        //        pricem = "0";
        //    }

        //    if (imgname != "")
        //    {
        //        imgsrc = "/UploadImgs/" + imgname;
        //        if (File.Exists(MapPath("/uploadTemp/" + imgname)))
        //        {
        //            File.Move(MapPath("/uploadTemp/" + imgname), MapPath("/UploadImgs/" + imgname));
        //        }
        //    }

        //    SqlDbHelper sdh = new SqlDbHelper();
        //    SqlParameter p1 = new SqlParameter("@ReleaseName", Session["userNick"]);
        //    SqlParameter p2 = new SqlParameter("@Information", infomation);
        //    SqlParameter p3 = new SqlParameter("@ExpectpricesMax", pricex);
        //    SqlParameter p4 = new SqlParameter("@ExpectpricesMin", pricem);
        //    SqlParameter p5 = new SqlParameter("@Responder", Session["userNick"]);
        //    SqlParameter p6 = new SqlParameter("@Respondcount",1);
        //    SqlParameter p7 = new SqlParameter("@Cateid", cate);
        //    SqlParameter p8 = new SqlParameter("@Parentcateid", pcid);
        //    SqlParameter p9 = new SqlParameter("@Overtime", datetime);
        //    SqlParameter p10 = new SqlParameter("@VolumeCount", 1);
        //    SqlParameter p11 = new SqlParameter("@Province", sheng);
        //    SqlParameter p12 = new SqlParameter("@City", shi);
        //    SqlParameter p13 = new SqlParameter("@Title", title);
        //    SqlParameter p14 = new SqlParameter("@Owner", owner);
        //    SqlParameter p15 = new SqlParameter("@imgsrc", imgsrc);
        //    SqlParameter p16 = new SqlParameter("@Count", count);
        //    SqlParameter p17 = new SqlParameter("@name", name);
        //    SqlParameter p18 = new SqlParameter("@Keyprop", keyprop);
        //    SqlParameter p19 = new SqlParameter("@cidtree", cidtree);
        //    SqlParameter p20 = new SqlParameter("@CatetextTree", cittextTree);

        //    SqlParameter[] paras = new SqlParameter[] { p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14, p15, p16, p17, p18, p19,p20 };


        //    return sdh.ExecuteNonQuery("sp_insertbuyinfo", CommandType.StoredProcedure, paras);
        //}

        private string bindcate()
        {
            string level = Request.QueryString["Glevel"];
            string parentcid = Request.QueryString["Gcid"];
            SqlDbHelper sdh = new SqlDbHelper();
            StringBuilder citstr = new StringBuilder();
            SystemLib slb = new SystemLib();
            string strsql = "";
            if (parentcid == "0")
            {
                strsql = "SELECT TOP 10 * FROM CidCount WHERE  Cidlevel = " + level + " AND [Count] > 0 ORDER BY [Count] DESC";
            }
            else
            {
                strsql = "SELECT * FROM CidCount WHERE  Cidlevel = " + level + " AND CHARINDEX('" + parentcid + "',cidtree) > 0 AND [Count] > 0";
            }
            DataTable dt = sdh.ExecuteDataTable(strsql);
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                string cateid = dt.Rows[i]["Cid"].ToString();
                string catelevel = dt.Rows[i]["Cidlevel"].ToString();
                //citstr.Append("<li><a href='#' onclick='cateclick("+ dt.Rows[i]["Cid"] +","+ dt.Rows[i]["Cidlevel"] +",this);return false;'>" + dt.Rows[i]["Name"].ToString().Trim() + "("+ dt.Rows[i]["count"] +")" +"</a></li>");
                citstr.Append("<li><a href='Search" + cateid  + catelevel + ".html' target='_blank'>" + dt.Rows[i]["Name"].ToString().Trim() + "(" + dt.Rows[i]["count"] + ")" + "</a></li>");
            }

            return citstr.ToString();
        }

        private string addbuy()
        {
            if (Session["userNick"] == null)
            {
                return "nouser";
            }
            string result = "";
            string buyname = Session["userNick"].ToString();
            string buyid = Request.Form["pid"];
            string selectsql = "SELECT Id FROM BuyersinfoR WHERE CHARINDEX(','+'" + buyname + "'+',',',' + Responder + ',') > 0 AND Id='" + buyid + "'";
            string updatesql = "UPDATE BuyersinfoR SET Responder = Responder + ',"+ buyname +"',Respondcount = Respondcount + 1 WHERE Id='" + buyid + "'";
            SqlDbHelper sdh = new SqlDbHelper();
            try
            {
                if (sdh.ExecuteScalar(selectsql) == null)
                {
                    sdh.ExecuteNonQuery(updatesql);
                    result = "ok";
                }
                else
                {
                    result = "already";
                }
            }
            catch (Exception)
            {
                result = "no";
            }
            return result;
        }

        private string regedit()
        {
            SqlDbHelper sdh = new SqlDbHelper();
            string user = Request.Form["UserName"];
            string getUser = "SELECT COUNT(*) FROM UserRegister WHERE userName = '" + user + "'";
            if (sdh.ExecuteScalar(getUser).ToString() != "0")
            {
                return "no";
            }
            else
            {
                return "ok";
            }
        }

        private string ipclick()
        {
            string sellid = Request.Form["sellid"];
            SqlDbHelper sdh = new SqlDbHelper();
            string user = Session["userNick"].ToString();
            string ip = GetUserIp();
            string checkip = "SELECT * FROM Userip WHERE username = '" + user + "' AND sellid = '" + sellid + "'";
            try
            {
                DataTable dt = sdh.ExecuteDataTable(checkip);
                if (dt.Rows.Count == 0)
                {
                    string insertip = "INSERT INTO Userip(username,ip,sellid,count) VALUES('" + user + "','" + ip + "','" + sellid + "',1)";
                    return sdh.ExecuteNonQuery(insertip).ToString();
                }
                else
                {
                    if (!dt.Rows[0]["ip"].ToString().Equals(ip))
                    {
                        string updateip = "UPDATE Userip SET ip='" + ip + "',count=count + 1 WHERE username = '" + user + "' AND sellid = '" + sellid + "'";
                        return sdh.ExecuteNonQuery(updateip).ToString();
                    }
                }

                return "";
            }
            catch (Exception ex)
            {
                return ex.Message;
            }

        }

        /// <summary>
        /// 获得用户IP
        /// </summary>
        private string GetUserIp()
        {
            // 穿过代理服务器取远程用户真实IP地址
            string Ip = string.Empty;
            if (Request.ServerVariables["HTTP_VIA"] != null)
            {
                if (Request.ServerVariables["HTTP_X_FORWARDED_FOR"] == null)
                {
                    if (Request.ServerVariables["HTTP_CLIENT_IP"] != null)
                    {
                        Ip = Request.ServerVariables["HTTP_CLIENT_IP"].ToString();
                    }
                    else
                    {
                        if (Request.ServerVariables["REMOTE_ADDR"] != null)
                        {
                            Ip = Request.ServerVariables["REMOTE_ADDR"].ToString();
                        }
                        else
                        {
                            Ip = "";
                        }
                    }
                }
                else
                {
                    Ip = Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
                }
            }
            else if (Request.ServerVariables["REMOTE_ADDR"] != null)
            {
                Ip = Request.ServerVariables["REMOTE_ADDR"].ToString();
            }
            else
            {
                Ip = "";
            }
            return Ip;
        }

        private string collect()
        {
            if (Session["userNick"] == null)
            {
                return "nouser";
            }
            string pid = Request.Form["pid"];
            string collstr = "INSERT INTO Collect(userid,buyerid) VALUES('" + Session["userNick"].ToString() + "','" + pid + "')";
            string chkcoll = "SELECT * FROM Collect WHERE userid='" + Session["userNick"].ToString() + "' AND buyerid = '" + pid + "'";

            SqlDbHelper sdh = new SqlDbHelper();
            try
            {
                if (sdh.ExecuteScalar(chkcoll) == null)
                {
                    sdh.ExecuteNonQuery(collstr);
                    return "ok";
                }
                else
                {
                    return "already";
                }
                
            }
            catch (Exception)
            {
                return "no";   
            }
        }


        private string getUser()
        {
            SqlDbHelper sdh = new SqlDbHelper();
            string user = Request.Form["username"];
            string userpass = FormsAuthentication.HashPasswordForStoringInConfigFile(Request.Form["userpass"], "MD5");
            //string isaddbuy = Request.Form["addbuy"];

            string getUser = "SELECT userName FROM UserRegister WHERE userName = '" + user + "' AND passWord = '" + userpass + "'";
            if (sdh.ExecuteScalar(getUser) == null)
            {
                return "no";
            }
            else
            {
                Session.Add("userNick", user);
                return "ok";
            }
        }
    }
}